#include "computethread.h"

#include <iostream>

ComputeThread::ComputeThread(QString n, QVector<QVector<Digit> > &t, int sleep, QSemaphore *s)
    : triangle(t), name(n), sleepTime(sleep)
{
    semaphore = s;
}

void ComputeThread::run()
{
    semaphore->acquire();

    for (int i = 0; i < triangle.size(); i++)
    {
        for (int j = 0; j < triangle[i].size(); j++)
        {
            int *tmp = triangle[i][j].getDigit();

            if ((*tmp) != 0) {
                triangle[i][j].finish();
                continue;
            }

            if (j == 0 || j == triangle[i].size() - 1) {
                (*tmp) = 1;
            }
            else {
                int first = 0;
                int second = 0;

                while(first == 0 || second == 0) {
                    first = (*triangle[i-1][j-1].getDigit());
                    triangle[i-1][j-1].finish();

                    second = (*triangle[i-1][j].getDigit());
                    triangle[i-1][j].finish();
                }

                (*tmp) = first + second;
            }

            std::cout << name.toStdString() << ": edycja " << i << \
                         " wiersza i " << j << " kolumny." << std::endl;

            triangle[i][j].finish();

            QThread::msleep(sleepTime);
        }
    }

    semaphore->release();

    exec();
}
